import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/entities/event/page_refresh_event.dart';
import 'package:library_base/entities/stock_out_child_entity.dart';
import 'package:library_base/entities/stock_out_entity.dart';
import 'package:library_base/event/event.dart';
import 'package:library_base/ext/list_ext.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:library_base/res/dividing_line.dart';
import 'package:library_base/res/gaps.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/route/routers.dart';
import 'package:library_base/utils/channel.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/widget/button/gradient_button.dart';
import 'package:library_base/widget/dialog/dialog_util.dart';
import 'package:library_base/widget/image/local_image.dart';
import 'package:library_base/widget/multi_state_widget/multi_state_widget.dart';
import 'package:library_base/base/base_list_state.dart';
import 'package:module_wms/page/outbound_orders/as_order/as_order_controller.dart';
import 'package:module_wms/page/outbound_orders/as_order/as_order_page_ui.dart';
import 'package:library_base/entities/event/wms_page_event.dart';

class AsOrderPage extends StatefulWidget {
  const AsOrderPage({Key? key}) : super(key: key);

  @override
  _AsOrderPageState createState() => _AsOrderPageState();
}

class _AsOrderPageState extends BaseListState<StockOutEntity, StockOutChildEntity, AsOrderPage,
    AsOrderController> {

  late StreamSubscription<WmsPageEvent> streamSubscription;

  late StreamSubscription<AsOrderPageRefreshEvent> refreshStreamSubscription;

  @override
  AsOrderController registerController() => Get.put(AsOrderController());

  MethodChannel fromAndroidChannel = const MethodChannel("AsOrderPageFlutter");

  @override
  void onCreate() {
    super.onCreate();
    setNavigationBarVisible(false);
    setStatusBarVisible(false);
    fromAndroidChannel.setMethodCallHandler(flutterMethod);
    streamSubscription = Event.eventBus.on<WmsPageEvent>().listen((event) {
      if(event.page == 0){
        if(mounted){
          showTimePicker();
        }else{
          ToastUtil.normal('加载中,请稍后');
        }
      }
    });

    refreshStreamSubscription = Event.eventBus.on<AsOrderPageRefreshEvent>().listen((event) {
      if(mounted){
        baseGetxController!.tryReLoad();
      }
    });
  }

  showTimePicker() {
    var map = <String, dynamic>{};
    if (baseGetxController!.stationTimeBegin.isNotEmpty) {
      map['currentTime'] = DateTime.parse(baseGetxController!.stationTimeBegin);
    } else {
      DateTime dateTime= DateTime.now();
      int milliseconds = dateTime.millisecondsSinceEpoch+1000*60*60*24;
      map['currentTime'] = DateTime.fromMillisecondsSinceEpoch(milliseconds);
    }
    map['filter'] = baseGetxController!.filter;
    map['reset'] = baseGetxController!.reset;
    DialogUtil.showTimePickDialog(arguments: map);
  }

  Future<dynamic> flutterMethod(MethodCall methodCall) async{
    switch (methodCall.method) {
      case TO_PRINTER_DETAIL_PAGE_CHANNEL:
        Get.toNamed(Routers.PRINT_DETAIL_PAGE,arguments: {"ids":baseGetxController!.stockOutIds});
        break;
    }
  }

  @override
  void controllerOnCreate() {
    useRefresh = true;
    isCanRefresh = true;
    isCanLoad = true;
    enableControlFinishLoad = true;
    enableControlFinishRefresh = true;
    baseGetxController?.easyRefreshController = controller;
  }

  @override
  Widget? getMainWidget(BuildContext context) {
    return MultiStateWidget(
      emptyWidget: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            LocalImage('base_empty', package: Constant.packLib(), width: 0.6.sw),
            Text(MultiLanguage.noSuchProduct.tr, style: TextStyles.textSecondary28),
            SizedBox(height: 80.w),
            Row(mainAxisAlignment: MainAxisAlignment.center, children: [
              GradientButton(
                ThemeUtil.getTheme(),
                width: 0.4.sw,
                height: 80.w,
                text: MultiLanguage.reload.tr,
                onPressed: baseGetxController!.tryReLoad,
              ),
              gapW24,
              GradientButton(
                ThemeUtil.getTheme(),
                width: 0.4.sw,
                height: 80.w,
                text: MultiLanguage.backToList.tr,
                onPressed: baseGetxController!.backToList,
              ),
            ])
          ]),
      controller: baseGetxController!.multiControllerOut,
      buildChild: (){
        return Stack(
          children: [
            Column(
              children: [
                GetBuilder<AsOrderController>(builder: (logic) {
                  return buildSearchWidget(baseGetxController!,onChanged: baseGetxController!.onChanged,onSearch: baseGetxController!.onSearch);
                }),
                Expanded(
                  child: Container(
                      color: ThemeUtil.getTheme().secondaryBgColor(),
                      child: getListView(context, baseGetxController)),
                ),
                buildBottom(
                  baseGetxController!.finishedCount,
                  baseGetxController!.totalCount,
                  baseGetxController!.enable,
                  baseGetxController!.isSelectedAll,
                  baseGetxController!.stockOutIds.length,
                  deliverGoods:baseGetxController!.deliverGoods,
                  print:baseGetxController!.print,
                  selectedAll:baseGetxController!.selectedAll,
                )
              ],
            ),
            // Positioned(
            //   right: 24.w,
            //   bottom: 200.w,
            //   child: GestureDetector(
            //       onTap: () {
            //
            //       },
            //       child: GetBuilder<AsOrderController>(
            //         builder: (logic) {
            //           return Opacity(
            //             opacity: 0.8,
            //             child: Container(
            //                 alignment: Alignment.centerRight,
            //                 child: LocalImage(baseGetxController!.isConnected.value?'common_bluetooth_connected':'common_bluetooth_no_connected',
            //                     package: Constant.packLib(),
            //                     width: 100.w,
            //                     height: 100.w,
            //                     fit: BoxFit.cover)),
            //           );
            //         },
            //       ),
            //   ),
            // )
          ],
        );
      },
      child: null,
    );
  }

  @override
  List<Widget> buildListItem(BuildContext context) {
    return baseGetxController!.listData.value.buildItem((index, element) {
      return GetBuilder<AsOrderController>(
        builder: (logic) {
          return buildItem(
            element,
            index,
            onCheck: baseGetxController!.onCheck,
            onExpand: _onExpand,
            toOrderDetail: baseGetxController!.toOrderDetail,
          );
        },
      );
    }, dividingLine: () {
      return line2;
    });
  }

  _onExpand() {
    baseGetxController!.update();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void onDestroy() {
    super.onDestroy();
    streamSubscription.cancel();
    refreshStreamSubscription.cancel();
  }

}
